package com.wut.clock.service.impl;

import com.wut.clock.entity.SysUser;
import com.wut.clock.mapper.SysUserMapper;
import com.wut.clock.mongo.dto.HistoryParams;
import com.wut.clock.mongo.repository.HistoryRepository;
import com.wut.clock.service.IHistoryService;
import com.wut.clock.util.ShiroUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ZYH
 * @unit D9Lab
 * @description 浏览历史实现类
 * @date 2022/6/11 17:19
 */
@Service
@RequiredArgsConstructor
public class HistoryServiceImpl implements IHistoryService {

    private final HistoryRepository historyRepository;

    private final SysUserMapper userMapper;

    @Override
    public int addHistory(HistoryParams historyParams) {
        SysUser user = userMapper.selectById(ShiroUtil.getUserId());
        historyParams.setUserId(user.getId());
        historyParams.setNickname(user.getNickname());
        historyParams.setAvatar(user.getAvatar());
        historyParams.setCreateTime(new Date());
        HistoryParams history = historyRepository.findByUserIdAndArticleId(user.getId(), historyParams.getArticleId());
        if(history != null){
            historyRepository.deleteByUserIdAndArticleId(user.getId(),historyParams.getArticleId());
        }
        historyRepository.save(historyParams);
        return 1;
    }

    @Override
    public int deleteHistory(List<String> ids) {
        List<HistoryParams> deleteList = new ArrayList<>();
        for(String id:ids){
            HistoryParams historyParams = new HistoryParams();
            historyParams.setId(id);
            deleteList.add(historyParams);
        }
        historyRepository.deleteAll(deleteList);
        return ids.size();
    }

    @Override
    public Page<HistoryParams> getHistoryList(Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum-1, pageSize);
        return historyRepository.findByUserIdOrderByCreateTimeDesc(ShiroUtil.getUserId(),pageable);
    }

    @Override
    public void clear() {
        historyRepository.deleteAllByUserId(ShiroUtil.getUserId());
    }
}
